// pages/message/chat/chat.js
var websocket = require('../../../utils/websocket')
const app = getApp()
import Notify from '@vant/weapp/notify/notify';
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		messages: [],
		user: {},
		friend: {},
		//输入框内容
		Input: '',
		sendmessage: '',
		scrollTop: 0,
		seemore:true,
    loading:false,
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad(options) {
		console.log(options)
		this.setData({
			friend: JSON.parse(options.id),
			user: wx.getStorageSync('user'),
		})
		if (options.messages != "undefined") {
			this.setData({
				messages: JSON.parse(options.messages)
			})
		}
		//接收所有的未读消息，并展示。调用后端接口从redis中删除未读消息。
	},


	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow() {
		this.removeBottom()
		websocket.getMessages((message) => {
			var message = JSON.parse(message)
			if (parseInt(message.fromId) == this.data.friend.id) {
				if (message.messageType == 4) {
					//存储消息到队列
					this.setData({
						messages: this.data.messages.concat(message)
					})
					this.removeBottom()
				}
				console.log(this.data.messages)
			} else {
				//看看外边是否可以接受message,可以就不管，不可以返回时做处理。可以，不管了
			}
		})
	},

	send() {
    if(this.data.sendmessage==''){
      Notify({
				type: 'danger',
				message: '请不要发送空消息'
			})
    }else{
      websocket.sendMsg({
        message: this.data.sendmessage, //发送内容
        to: this.data.friend.id
      }, () => {
        Notify({
          type: 'primary',
          message: '成功发送消息'
        })
        var message = {
          fromId: this.data.user.id,
          toId: this.data.friend.id,
          time: Date.parse(new Date()),
          messageType: "4",
          message: this.data.sendmessage
        }
        this.setData({
          messages: this.data.messages.concat(message),
          sendmessage: ''
        })
        console.log(this.data.messages)
        this.removeBottom()
      })
    }
	},
	setTemp() {
		var page = getCurrentPages();
		var lastPage = page[page.length - 2]
		if (page == undefined || page == null) return;
		lastPage.setTemp()
		console.log(lastPage.data.temp)
	},
	onClickLeft() {
		this.setTemp()
		this.deleteUnread()
		wx.navigateBack({
			delta: 1,
		})
	},
	deleteUnread(){
		app.request({
			url: app.globalData.apiUrl + "/message/"+this.data.user.id+'/'+this.data.friend.id,
			method: 'DELETE',
		}).then(res => {
			if (res.statusCode == 200) {
			} else {
				Notify('服务错误，稍后重试');
			}
		})
	},
	InputFocus() {},
	InputBlur(e) {
		this.setData({
			sendmessage: e.detail.value
    })
    console.log(e)
    console.log(this.data.sendmessage)
	},
	removeBottom() {
		let that = this;
		wx.createSelectorQuery().select('#chatBody').boundingClientRect(function (rect) {
			wx.pageScrollTo({
				scrollTop: rect.height,
				duration: 100 // 滑动速度
			})
			that.setData({
				scrollTop: rect.height - that.data.scrollTop
			});
		}).exec();

	},
	gotoShow(e){
    console.log(e)
		wx.navigateTo({
			url: '/pages/show/show?id='+e.currentTarget.dataset.id,
		})
  },
  gethistory(){
    this.setData({
      loading:true,
      seemore:false
    })
    console.log(this.data.loading)
    app.request({
			url: app.globalData.apiUrl + "/message/"+this.data.user.id+'/'+this.data.friend.id,
			method: 'GET',
		}).then(res => {
			if (res.statusCode == 200) {
        var arr=res.data.data
        var temp=this.data.messages
        console.log(arr)
        for(var i=0;i<arr.length;i++){
          temp=temp.concat(JSON.parse(arr[i]))
        }
        temp.sort(function(a,b){
          return  b.time> a.time? -1 : 1
        })
        this.setData({
          messages:temp,
          loading:false
        })
			} else {
				Notify('服务错误，稍后重试');
			}
		})
  }
})